package com.lechuang.yilinjia.view.activity.jiukuaijiu;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lechuang.yilinjia.R;
import com.lechuang.yilinjia.base.BaseFragment;
import com.lechuang.yilinjia.base.Constants;
import com.lechuang.yilinjia.mine.adapter.CommonRecyclerAdapter;
import com.lechuang.yilinjia.mine.adapter.OnItemClick;
import com.lechuang.yilinjia.mine.adapter.ViewHolderRecycler;
import com.lechuang.yilinjia.mine.view.XRecyclerView;
import com.lechuang.yilinjia.model.LeCommon;
import com.lechuang.yilinjia.model.bean.HomeSearchResultBean;
import com.lechuang.yilinjia.presenter.net.Netword;
import com.lechuang.yilinjia.presenter.net.ResultBack;
import com.lechuang.yilinjia.presenter.net.netApi.HomeApi;
import com.lechuang.yilinjia.utils.Utils;
import com.lechuang.yilinjia.view.activity.home.ProductDetailsActivity;
import com.lechuang.yilinjia.view.defineView.GridItemDecoration;
import com.lechuang.yilinjia.view.defineView.SpannelTextViewGrid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者：li on 2017/9/21 17:46
 * 邮箱：961567115@qq.com
 * 修改备注:
 */
public class JiuKuaiJiuFragment extends BaseFragment  {

    private TextView tv_nine,tv_nineteen;
    private  View content;
    private RelativeLayout common_loading_all;
    private long mTime;
    //参数map
    private HashMap<String, String> allParamMap;
    //可以刷新的gridview
    private XRecyclerView rv_product;
    private CommonRecyclerAdapter mAdapter;
    //无网络状态
    private LinearLayout ll_notNet;
    //刷新重试按钮
    private ImageView iv_tryAgain;
    private List<HomeSearchResultBean.ProductListBean> productList;
    private ImageView iv_price;
    //保存用户登录信息的sp
    private SharedPreferences se;
    private LinearLayoutManager mLayoutManager;
    public boolean isBottom = false;
    //首页分类
    Unbinder unbinder;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        content = inflater.inflate(R.layout.fragment_jiukuaijiu, null, false);

        unbinder = ButterKnife.bind(this, content);

        initView();
        return content;
    }

    //初始化view
    private void initView() {
        //保存用户登录信息的sp
        se = PreferenceManager.getDefaultSharedPreferences(getActivity());
        //商品集合
        productList = new ArrayList<>();
        allParamMap = new HashMap<>();
        //刷新重试
        iv_tryAgain = (ImageView) content.findViewById(R.id.iv_tryAgain);
        ll_notNet = (LinearLayout) content.findViewById(R.id.ll_noNet);
        common_loading_all = (RelativeLayout) content.findViewById(R.id.common_loading_all);
        iv_price = (ImageView) content.findViewById(R.id.iv_price);
        rv_product = (XRecyclerView) content.findViewById(R.id.rv_product);
        tv_nine = (TextView) content.findViewById(R.id.tv_nine);
        tv_nineteen = (TextView) content.findViewById(R.id.tv_nineteen);




        rv_product.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isBottom = false;
                page = 1;
                if (null != productList) {
                    productList.clear();
                    if (mAdapter != null)
                        mAdapter.notifyDataSetChanged();
                }
                getData();

            }

            @Override
            public void onLoadMore() {
                page += 1;
                getData();
            }
        });

        rv_product.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (productList.size() - mLayoutManager.findLastVisibleItemPosition() < 5) {
                    if (System.currentTimeMillis() - mTime > 1000 && !isBottom) {
                        page += 1;
                        getData();
                    }
                }
            }
        });

        getData();
    }

    //网络请求获取数据
    private void getData() {
        if(page == 1){
            common_loading_all.setVisibility(View.VISIBLE);
        }
        mTime = System.currentTimeMillis();
        if (allParamMap != null) {
            allParamMap.clear();
        }
        if (Utils.isNetworkAvailable(getActivity())) {
            ll_notNet.setVisibility(View.GONE);
            allParamMap.put("page", page + "");
            //9.9  19.9
            allParamMap.put("type", type);

            if (showStyle == 0) {
                //按销量
                allParamMap.put("isVolume", 1 + "");
            } else if (showStyle == 1) {
                //按好评排序
                allParamMap.put("isAppraise", 1 + "");
            } else if (showStyle == 2) {
                //按价格排序
                /**
                 * isPrice 1 价格从低到高排序
                 * isPrice 2 价格从高到低排序
                 */
                if (isHighToDown) {
                    //价格从高到低
                    allParamMap.put("isPrice", 2 + "");
                } else {
                    allParamMap.put("isPrice", 1 + "");
                }
            } else if (showStyle == 3) {
                //按新品排序
                allParamMap.put("isNew", 1 + "");
            }
            Netword.getInstance().getApi(HomeApi.class)
                    .searchResult(allParamMap)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ResultBack<HomeSearchResultBean>(getActivity()) {
                        @Override
                        public void successed(HomeSearchResultBean result) {
                            common_loading_all.setVisibility(View.GONE);
                            if (result == null) {
                                return;
                            }

                            List<HomeSearchResultBean.ProductListBean> list = result.productList;

//                            nothingData.setVisibility(View.GONE);
                            if (page > 1 && list.isEmpty()) {
//                                showShortToast("亲!已经到底了");
                                rv_product.noMoreLoading();
                                isBottom = true;
                                return;
                            }
                            for (int i = 0; i < list.size(); i++) {
                                productList.add(list.get(i));
                            }
                            //只有page=1 的时候设置适配器 下拉刷新直接调用notifyDataSetChanged()
                            if (1 == page) {
                                if (mAdapter == null) {
                                    mAdapter = new CommonRecyclerAdapter(getActivity(), R.layout.item_jiukuaijiu_product, productList) {
                                        @Override
                                        public void convert(ViewHolderRecycler viewHolder, Object data) {
                                            try {
                                                HomeSearchResultBean.ProductListBean bean = (HomeSearchResultBean.ProductListBean) data;
                                                viewHolder.displayImage(R.id.iv_img, bean.imgs);
                                                //原件
                                                TextView view = viewHolder.getView(R.id.tv_oldprice);
                                                TextView tv_zhuan = viewHolder.getView(R.id.tv_zhuan);
                                                view.setText(bean.price);
                                                if (se.getInt(LeCommon.KEY_AGENCY_STATUS, 0) == 1) {
                                                    if (bean.zhuanMoney != null) {
                                                        tv_zhuan.setVisibility(View.VISIBLE);
                                                        tv_zhuan.setText(bean.zhuanMoney);
                                                    } else {
                                                        tv_zhuan.setVisibility(View.INVISIBLE);
                                                    }
                                                } else {
                                                    tv_zhuan.setVisibility(View.GONE);
                                                }
                                                //销量
                                                viewHolder.setText(R.id.tv_number, "已抢" + bean.nowNumber + "件");
                                                // 中划线
                                                view.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
                                                //新件
                                                viewHolder.setText(R.id.tv_nowprice, "券后价¥" + bean.preferentialPrice);
                                                SpannelTextViewGrid view1 = viewHolder.getView(R.id.tv_name);
                                                view1.setShopType(Integer.parseInt(bean.shopType));
                                                view1.setDrawText(bean.name);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    };

                                    mLayoutManager = new GridLayoutManager(getActivity(), 2);
                                    mLayoutManager.setSmoothScrollbarEnabled(true);

                                    rv_product.addItemDecoration(new GridItemDecoration(
                                            new GridItemDecoration.Builder(getActivity())
                                                    .isExistHead(true)
                                                    .margin(8,8)
                                                    .horSize(10)
                                                    .verSize(10)
                                                    .showLastDivider(true)
                                    ));

                                    rv_product.setNestedScrollingEnabled(false);
                                    rv_product.setLayoutManager(mLayoutManager);
                                    rv_product.setAdapter(mAdapter);
                                    mAdapter.setOnItemClick(new OnItemClick() {
                                        @Override
                                        public void itemClick(View v, int position) {
                                            startActivity(new Intent(getActivity(), ProductDetailsActivity.class)
                                                    .putExtra(Constants.listInfo, JSON.toJSONString(productList.get(position))));
                                        }
                                    });
                                }
                            } else {

                            }

                            mAdapter.notifyDataSetChanged();
                            rv_product.refreshComplete();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            common_loading_all.setVisibility(View.GONE);
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                            common_loading_all.setVisibility(View.GONE);
                        }
                    });
        } else {
            ll_notNet.setVisibility(View.VISIBLE);
        }

    }






    //价格从高到底
    private boolean isHighToDown = true;
    //搜索结果展示的方式  0:按销量展示  1.按好评展示 2.按价格展示  3.按新品展示
    private int showStyle = 0;
    /**
     * 入参的排序方式
     * isVolume 1代表按销量排序从高到底
     * isAppraise 1好评从高到底
     * isPrice  1价格从低到高排序
     * isPrice  2价格从高到低排序
     * isNew    1新品商品冲最近的往后排序
     */
    private String style = "isVolume=1";
    //入参 页数
    private int page = 1;
    //入参 9.9 = 2  19.9 = 10
    private String type = "2";

    @OnClick({R.id.tv_nine, R.id.tv_nineteen,R.id.ll_sale,R.id.ll_like,R.id.ll_price,R.id.ll_new})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //9.9
            case R.id.tv_nine:
                tv_nine.setBackground(getResources().getDrawable(R.drawable.bg_solid_white_jiukuaijiu));
                tv_nine.setTextColor(getResources().getColor(R.color.main));
                tv_nineteen.setBackground(getResources().getDrawable(R.drawable.bg_solid_main_jiukuaijiu));
                tv_nineteen.setTextColor(getResources().getColor(R.color.white));
                type = "2";
                page = 1;
                if (productList != null)
                    productList.clear();
                if (mAdapter != null)
                    mAdapter.notifyDataSetChanged();
                getData();
                break;
            //19.9
            case R.id.tv_nineteen:
                tv_nine.setBackground(getResources().getDrawable(R.drawable.bg_solid_main_jiukuaijiu));
                tv_nine.setTextColor(getResources().getColor(R.color.white));
                tv_nineteen.setBackground(getResources().getDrawable(R.drawable.bg_solid_white_jiukuaijiu));
                tv_nineteen.setTextColor(getResources().getColor(R.color.main));
                type = "10";
                page = 1;
                if (productList != null)
                    productList.clear();
                if (mAdapter != null)
                    mAdapter.notifyDataSetChanged();
                getData();
                break;

            case R.id.ll_sale: //按销量排序
                //style = "isVolume=1";
                showStyle = 0;
                selectShowStyle(showStyle);
                page = 1;
                if (productList != null)
                    productList.clear();
                if (mAdapter != null)
                    mAdapter.notifyDataSetChanged();
                getData();
                break;
            case R.id.ll_like://按好评排序
                //style = "isAppraise=1";
                showStyle = 1;
                selectShowStyle(showStyle);
                page = 1;
                if (productList != null)
                    productList.clear();
                if (mAdapter != null)
                    mAdapter.notifyDataSetChanged();
                getData();
                break;
            case R.id.ll_price: //按价格排序

                /**
                 * isPrice 1 价格从低到高排序
                 * isPrice 2 价格从高到低排序
                 */
                showStyle = 2;
                selectShowStyle(showStyle);
                if (isHighToDown) {
                    //价格从高到低
                    //style = "isPrice=2";
                    iv_price.setImageResource(R.drawable.shousuohou_jiage_shang);
                    isHighToDown = !isHighToDown;
                    page = 1;
                    if (productList != null)
                        productList.clear();
                    if (mAdapter != null)
                        mAdapter.notifyDataSetChanged();
                    getData();

                } else {
                    // style = "isPrice=1";
                    iv_price.setImageResource(R.drawable.sousuohou_jiage_xia);
                    isHighToDown = !isHighToDown;
                    page = 1;
                    if (productList != null)
                        productList.clear();
                    if (mAdapter != null)
                        mAdapter.notifyDataSetChanged();
                    getData();
                }
                break;
            case R.id.ll_new:  //按新品排序
                //style = "isNew=1";
                showStyle = 3;
                selectShowStyle(showStyle);
                page = 1;
                if (productList != null)
                    productList.clear();
                if (mAdapter != null)
                    mAdapter.notifyDataSetChanged();
                getData();
                break;
//            case R.id.common_nothing_data:
//                page = 1;
//                if (null != productList)
//                    productList.clear();
//                if (mAdapter != null)
//                    mAdapter.notifyDataSetChanged();
//                getData();
//                break;

            default:
                break;
        }
    }

    //选择展示的方式
    private void selectShowStyle(int showStyle) {

        if (showStyle == 0) {
            changeStyle(showStyle);
        } else if (showStyle == 1) {
            changeStyle(showStyle);
        } else if (showStyle == 2) {
            changeStyle(showStyle);
        } else if (showStyle == 3) {
            changeStyle(showStyle);
        }
    }

    private void changeStyle(int showStyle) {

        View[] v = {content.findViewById(R.id.tv_sale), content.findViewById(R.id.tv_like),
                content.findViewById(R.id.tv_price), content.findViewById(R.id.tv_new)};
        View[] v1 = {content.findViewById(R.id.v_sale), content.findViewById(R.id.v_like)
                , content.findViewById(R.id.v_price), content.findViewById(R.id.v_new)};
        for (int i = 0; i < v.length; i++) {
            ((TextView) v[i]).setTextColor(getResources().getColor(R.color.black));
        }
        for (int i = 0; i < v1.length; i++) {
            v1[i].setVisibility(View.GONE);
        }

        ((TextView) v[showStyle]).setTextColor(getResources().getColor(R.color.main));
        v1[showStyle].setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
